package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/10/11 11:13
 */

@Component
public class SpringSecurityUserService implements UserDetailsService {

    //使用dubbo通过网络远程调用服务提供方获取数据库中的用户信息
    @Reference
    private UserService userService;

    //根据用户名查询数据库获取用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用service中的根据姓名查询到一个user用户;
        User user = userService.findByUsername(username);
        //判断如果user不为空;
        //如果是空,说明没有这个用户信息,return null;结束方法;
        if (user == null) {
            //用户名不存在;
            return null;
        }
        //创建一个集合,为角色授权;
        List<GrantedAuthority> list = new ArrayList<>();
        //动态为当前用户授权
        Set<Role> roles = user.getRoles();
        //判断获取到的roles集合是否为空,增强代码的健壮性;
        if (roles != null && roles.size() > 0) {
            //遍历角色集合;
            for (Role role : roles) {
                //为用户授予角色;
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                //获取权限集合;
                Set<Permission> permissions = role.getPermissions();
                if (permissions != null && permissions.size() > 0) {
                    //遍历权限集合;
                    for (Permission permission : permissions) {
                        //为用户授予权限;
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return securityUser;
    }
}
